package com.dtsz.m2.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.Request;
import com.dtsz.m2.R;
import com.dtsz.m2.config.UrlConfig;
import com.dtsz.m2.lockpattern.util.LockPatternUtil;
import com.dtsz.m2.lockpattern.widget.LockPatternView;
import com.dtsz.m2.ui.base.BaseActivity;
import com.dtsz.m2.ui.model.Users;
import com.dtsz.m2.utils.cache.ACache;
import com.dtsz.m2.utils.constant.Constant;
import com.dtsz.m2.volley.state.HUCState;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Sym on 2015/12/24.
 */
public class GestureLoginActivity extends BaseActivity {

    private static final String TAG = "LoginGestureActivity";

    LockPatternView lockPatternView;
    TextView messageTv;
    Button forgetGestureBtn;

    private ACache aCache;
    private static final long DELAYTIME = 600l;
    private byte[] gesturePassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_gesture_login);
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        tvActionbarTitle.setText("支付");
        //  ButterKnife.bind(this);
        lockPatternView = findViewById(R.id.lockPatternView);
        messageTv = findViewById(R.id.messageTv);
        forgetGestureBtn = findViewById(R.id.forgetGestureBtn);
//        String userId = getIntent().getExtras().getString("userId");//账号ID
//        String money = getIntent().getExtras().getString("money");//充值金额
//        String ecologyId = getIntent().getExtras().getString("ecologyId");//项目ID
        String orderId = getIntent().getExtras().getString("URL");
        pageVo.setId(orderId);
        this.init();
    }

    private void init() {
        aCache = ACache.get(GestureLoginActivity.this);
        //得到当前用户的手势密码
        gesturePassword = aCache.getAsBinary(Constant.GESTURE_PASSWORD);
        lockPatternView.setOnPatternListener(patternListener);
        updateStatus(Status.DEFAULT);
    }

    private LockPatternView.OnPatternListener patternListener = new LockPatternView.OnPatternListener() {

        @Override
        public void onPatternStart() {
            lockPatternView.removePostClearPatternRunnable();
        }

        @Override
        public void onPatternComplete(List<LockPatternView.Cell> pattern) {
            if (pattern != null) {
                if (LockPatternUtil.checkPattern(pattern, gesturePassword)) {
                    updateStatus(Status.CORRECT);
                } else {
                    gesturePassword = LockPatternUtil.patternToHash(pattern);
                    updateStatus(Status.CORRECT);
                }
            }
        }
    };

    /**
     * 更新状态
     *
     * @param status
     */
    private void updateStatus(Status status) {
        messageTv.setText(status.strId);
        messageTv.setTextColor(getResources().getColor(status.colorId));
        switch (status) {
            case DEFAULT:
                lockPatternView.setPattern(LockPatternView.DisplayMode.DEFAULT);
                break;
            case ERROR:
                lockPatternView.setPattern(LockPatternView.DisplayMode.ERROR);
                lockPatternView.postClearPatternRunnable(DELAYTIME);
                break;
            case CORRECT:
                lockPatternView.setPattern(LockPatternView.DisplayMode.DEFAULT);
                loginGestureSuccess();
                break;
        }
    }

    /**
     * 手势登录成功（去首页） 李宗恩
     */
    private void loginGestureSuccess() {
        //Toast.makeText(GestureLoginActivity.this, "success", Toast.LENGTH_SHORT).show();
        loading();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < gesturePassword.length; i++) {
            sb.append(gesturePassword[i] + "");
        }
        pageVo.setRsa(sb.toString());
        hucRequestInterfase.executeStr(this, Users.class,
                HUCState.HUC_REQEUST_CODE_1, Request.Method.POST, UrlConfig.INWARDTURN_URL,
                hucParameInterfase.getRequestParameter(pageVo), true);
    }

    @Override
    public void onSuccessfulStrType(int inputType, Object response) {
        super.onSuccessfulStrType(inputType, response);
        switch (inputType) {
            case HUCState.HUC_REQEUST_CODE_1:
                String str = (String) response;
                if ("转出成功".equals(str)) {
                    this.finish();
                }
                showToast(str);
                break;
        }
        loadDismiss();
    }

    /**
     * 忘记手势密码（去账号登录界面）
     */
    @OnClick(R.id.forgetGestureBtn)
    void forgetGesturePasswrod() {
        Intent intent = new Intent(GestureLoginActivity.this, RetrievePasswordActivity.class);
        startActivity(intent);
        this.finish();
    }

    private enum Status {
        //默认的状态
        DEFAULT(R.string.gesture_default, R.color.grey_a5a5a5),
        //密码输入错误
        ERROR(R.string.gesture_error, R.color.red_f4333c),
        //密码输入正确
        CORRECT(R.string.gesture_correct, R.color.grey_a5a5a5);

        private Status(int strId, int colorId) {
            this.strId = strId;
            this.colorId = colorId;
        }

        private int strId;
        private int colorId;
    }
}
